<?php

namespace apiend\modules\user\models;

use Yii;
use yii\base\InvalidParamException;
use yii\web\UnauthorizedHttpException;
use yii\db\Exception;
use common\base\Model;
use common\models\user\UserMeta;
use common\models\user\UserHobby;
use common\helpers\ArrayHelper;

/**
 * 个人信息修改模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class ProfileForm extends Model {

    /**
     * @var string $avatar 头像
     */
    public $avatar;

    /**
     * @var string $nickname 昵称
     */
    public $nickname;

    /**
     * @var string $realname 姓名
     */
    public $realname;

    /**
     * @var string $marriage 婚姻状况
     */
    public $marriage;

    /**
     * @var string $hobby 爱好类别
     */
    public $hobby = null;

    /**
     * @var string $children 子女数
     */
    public $children;

    /**
     * @var string $gender 性别
     */
    public $gender;

    /**
     * @var string $birthday 出生日期
     */
    public $birthday;

    /**
     * @var string $location 位置
     */
    public $location;

    /**
     * @var UserMeta $_user
     */
    private $_user = null;

    public function __construct($id, $config = array()) {
        if (!$id) {
            throw new UnauthorizedHttpException('Your request was made with invalid credentials.');
        }
        if (!$this->setUser($id)) {
            throw new InvalidParamException('User is null.');
        }
        parent::__construct($config);
    }

    public function scenarios() {
        $scenarios = parent::scenarios();
        $scenarios['educater'] = ['nickname', 'avatar'];
        return $scenarios;
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [
                'nickname',
                'required',
                'when' => function ($model) {
                    return empty($model->avatar);
                },
                'on' => 'educater'
            ],
            [
                'avatar',
                'required',
                'when' => function ($model) {
                    return empty($model->nickname);
                },
                'on' => 'educater'
            ],
            ['avatar', 'string', 'max' => 255],
            ['nickname', 'string', 'max' => 30],
            ['gender', 'in', 'range' => [0, 1, 2]],
            [['gender', 'children', 'marriage'], 'integer'],
            ['birthday', 'date', 'format' => 'yyyy-MM-dd'],
            [['realname', 'location'], 'string', 'max' => 50],
            ['hobby', 'safe'],
        ];
    }

    /**
     * @return \common\models\user\UserMeta|null
     */
    protected function getUser() {
        return $this->_user;
    }

    /**
     * @return \api\models\UserCompatibleModel|null
     */
    protected function setUser($id) {
        return $this->_user = UserMeta::findOne($id);
    }

    public function save() {
        if (!$this->validate()) {
            $this->dumpError('', $this->getFirstErrors());
        }
        /* @var $model \common\models\user\UserMeta */
        $model = $this->getUser();
        $model->setAttributes(array_filter($this->attributes));

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
            $modelid = $model->id;
            //多分类写入保存
            if ($this->hobby !== null) {
                $hobbys = array_filter(array_unique(explode(',', $this->hobby)));
                if (!empty($hobbys)) {
                    $tempHobbys = ArrayHelper::map($model->hobbys, 'id', 'course_category_id');
                    $intersect = array_intersect($tempHobbys, $hobbys);
                    $remove = array_diff($tempHobbys, $intersect);
                    UserHobby::deleteAll(['id' => array_keys($remove)]);
                    $newHobbys = array_diff($hobbys, $intersect);
                    $hobby = new UserHobby();
                    foreach ($newHobbys as $cateid) {
                        $_hobby = clone $hobby;
                        $_hobby->attributes = [
                            'user_id' => $modelid,
                            'course_category_id' => $cateid,
                        ];
                        if (!$_hobby->save()) {
                            throw new Exception(print_r($_hobby->getErrors(), true));
                        }
                    }
                } else {
                    UserHobby::deleteAll(['user_id' => $model->id]);
                }
            }

            $transaction->commit();
        } catch (Exception $e) {
            // 记录回滚（事务回滚）
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
            return false;
        }
        return $model;
    }

}
